package com.memexue.order.message;

import com.memexue.common.ProductInfoOutput;
import com.memexue.core.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ProductInfoReceiver {
    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String msg){
        try {
            List<ProductInfoOutput> outputList = JacksonUtils.json2list(msg, ProductInfoOutput.class);
            log.info("从队列{}接收到商品信息{}", "productInfo", outputList);
            // 获取到数据之后把信息存到redis
            for(ProductInfoOutput output : outputList){
                // key是id，value是库存
                stringRedisTemplate.opsForValue().set(
                        String.format(PRODUCT_STOCK_TEMPLATE, output.getProductId()),
                        String.valueOf(output.getProductStock()));
            }
        } catch (Exception e) {
            log.error("ProductInfoReceiver receive error", e);
        }
    }
}
